<?php
/**
 * LICENSE
 * 
 * [license information]
 * 
 * @category   plugins 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 */
require_once 'Nine/Plugin.php';
require_once 'geoiploc.php';
class AutoDetectLanguage extends Nine_Plugin
{

    /**
     * Called before Zend_Controller_Front begins evaluating the
     * request against its routes.
     *
     * @param Zend_Controller_Request_Abstract $request
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
		$langCode  = @$_COOKIE['lang_code_' . Nine_Registry::getAppName()];
		$pLangCode = @$_COOKIE['p_lang_code_' . Nine_Registry::getAppName()];
		
		/**
		 * Detect language by IP
		 */
    	if(null == $pLangCode){
    		/**
    		 * First time to visit
    		 */
			$ip = @$_SERVER['REMOTE_ADDR']; // get ip of current country 
//			$ip = '58.186.228.205'; #ip of VN
//			$ip = '31.207.3.42'; #ip of CZ
			$country  = @getCountryFromIP($ip);
			$langCode = ('VN' == $country)?'vi':'en';
			Nine_Registry::set('langCode', strtolower($langCode));	 
			setcookie('lang_code_' . Nine_Registry::getAppName(), $langCode, time() + 31536000, Nine_Registry::getBaseUrl());
			setcookie('p_lang_code_' . Nine_Registry::getAppName(), $langCode, time() + 31536000, Nine_Registry::getBaseUrl());
    	}
    	/**
    	 * Always display langCode in URL for multilingual site because of SEO link issue.
    	 */
        if (true == Nine_Registry::get('withoutLangCode') && false === @Nine_Registry::getConfig('usingOneLanguage')) {
       		Nine_Registry::set('APP_BASE_URL', Nine_Registry::getAppBaseUrl() . "{$langCode}/");
        }
            
		
    }  
    
}